#!/bin/sh
#
# Merge from branch

PAGER=${DIFF_PAGER:=${PAGER:=less}}

usage()
{
	cat << EOT >&2
usage:
  $0 branch -c M:N...
  $0 branch -r M[,N...]
EOT
	exit 1
}

# Ensure the repository is up-to-date before doing anything.
if ! svn update; then
	echo "*** Repository update failed!" >&2
	exit 1
fi

out=`svn status | grep -v '^?'`
if [ -n "${out}" ]; then
	echo "*** Repository has local modifications!" >&2
	exit 1
fi

_c=""
_r=""

_branch="$1"; shift

if [ -z "${_branch}" ]; then
	usage
fi

args=`getopt c:r: $*`
if [ $? -ne 0 ]; then
	usage
fi
set -- $args

for i
do
	case "$i" in
		-c) _c="$2"; shift; shift;;
		-r) _r="$2"; shift; shift;;
		--) shift; break;;
	esac
done

if [ -z "${_c}${_r}" -o -n "${_c}" -a -n "${_r}" ]; then
	usage
fi

repo_root=`LC_ALL=C svn info | awk ' $1 == "URL:" { print $2 } ' | sed -E -e 's|/trunk($\|/.*)||'`
repo_branch="${repo_root}/branches/${_branch}"

source=""
if [ -n "${_c}" ]; then
	svn merge -c "${_c}" ${repo_branch} || exit 1
	source="changeset ${_c}"
else
	svn merge -r "${_r}" ${repo_branch} || exit 1
	source="revision ${_r}"
fi

if [ $? -eq 0 ]; then
	ans=""
	while [ "$ans" != "yes" -a "$ans" != "no" ]; do
		svn diff | ${PAGER}
		echo -n "Commit this? (yes/no) "
		read ans
	done
	if [ "$ans" = "yes" ]; then
		svn commit -m "MFB (${_branch}) ${source}."
	fi
fi

